<template>
  <div class="progress-dashboard">
    <!-- 概览统计卡片 -->
    <div class="stats-overview">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon study-time">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats?.formattedStudyTime || '0分钟' }}</div>
              <div class="stat-label">总学习时长</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon study-days">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats?.continuousStudyDays || 0 }}天</div>
              <div class="stat-label">连续学习</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon courses">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats?.coursesStudied || 0 }}</div>
              <div class="stat-label">学习课程</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon notes">
              <el-icon><EditPen /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats?.notesCreated || 0 }}</div>
              <div class="stat-label">创建笔记</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="16" class="charts-section">
      <!-- 每日学习时长图表 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>每日学习时长</span>
              <el-select v-model="dailyChartDays" @change="loadStats" size="small">
                <el-option label="最近7天" :value="7" />
                <el-option label="最近15天" :value="15" />
                <el-option label="最近30天" :value="30" />
              </el-select>
            </div>
          </template>
          <div ref="dailyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 学习类型分布饼图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>学习类型分布</span>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="charts-section">
      <!-- 课程学习排行 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>课程学习时长排行</span>
          </template>
          <div class="course-ranking">
            <div 
              v-for="(course, index) in (stats?.courseRanking ? stats.courseRanking.slice(0, 8) : [])" 
              :key="course.courseId"
              class="ranking-item"
            >
              <div class="ranking-number">{{ index + 1 }}</div>
              <div class="course-info">
                <div class="course-title">{{ course.courseTitle || `课程${course.courseId}` }}</div>
                <div class="study-time">{{ course.formattedTime }}</div>
              </div>
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="{ width: `${getRelativeProgress(course, stats?.courseRanking || [])}%` }"
                ></div>
              </div>
            </div>
            <div v-if="!stats?.courseRanking?.length" class="empty-state">
              暂无学习数据
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 学习热力图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>学习时间热力图</span>
          </template>
          <div class="heatmap-container">
            <div class="heatmap-grid">
              <div 
                v-for="hour in 24" 
                :key="hour-1"
                class="heatmap-cell"
                :class="getHeatmapIntensity(hour-1)"
                :title="`${hour-1}:00 - ${hour}:00: ${getHourStudyTime(hour-1)}`"
              >
                <span class="hour-label">{{ hour-1 }}</span>
              </div>
            </div>
            <div class="heatmap-legend">
              <span>学习强度：</span>
              <div class="legend-scale">
                <div class="legend-item low"></div>
                <div class="legend-item medium"></div>
                <div class="legend-item high"></div>
                <div class="legend-item very-high"></div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习目标进度 -->
    <el-card class="goals-card">
      <template #header>
        <div class="card-header">
          <span>学习目标进度</span>
          <el-button type="primary" size="small" @click="showGoalDialog = true">
            设置目标
          </el-button>
        </div>
      </template>
      
      <div class="goals-grid">
        <div class="goal-item">
          <div class="goal-icon">🎯</div>
          <div class="goal-content">
            <div class="goal-title">每日学习目标</div>
            <div class="goal-progress">
              <el-progress 
                :percentage="dailyGoalProgress" 
                :color="getProgressColor(dailyGoalProgress)"
                :show-text="false"
              />
              <span class="progress-text">{{ dailyStudyTime }} / {{ dailyGoalTime }}</span>
            </div>
          </div>
        </div>
        
        <div class="goal-item">
          <div class="goal-icon">📚</div>
          <div class="goal-content">
            <div class="goal-title">每周学习目标</div>
            <div class="goal-progress">
              <el-progress 
                :percentage="weeklyGoalProgress" 
                :color="getProgressColor(weeklyGoalProgress)"
                :show-text="false"
              />
              <span class="progress-text">{{ weeklyStudyTime }} / {{ weeklyGoalTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 目标设置对话框 -->
    <el-dialog v-model="showGoalDialog" title="设置学习目标" width="500px">
      <el-form :model="goalForm" label-width="100px">
        <el-form-item label="每日目标">
          <el-input-number 
            v-model="goalForm.dailyMinutes" 
            :min="15" 
            :max="480"
            :step="15"
          /> 分钟
        </el-form-item>
        <el-form-item label="每周目标">
          <el-input-number 
            v-model="goalForm.weeklyHours" 
            :min="1" 
            :max="40"
            :step="1"
          /> 小时
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showGoalDialog = false">取消</el-button>
        <el-button type="primary" @click="saveGoals">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Clock, Calendar, Reading, EditPen } from '@element-plus/icons-vue'
import { analyticsApi, type LearningStats } from '@/api/analytics'
import * as echarts from 'echarts'

// 响应式数据
const stats = ref<LearningStats>()
const loading = ref(false)
const dailyChartDays = ref(7)
const showGoalDialog = ref(false)

// 图表引用
const dailyChartRef = ref<HTMLElement>()
const typeChartRef = ref<HTMLElement>()
let dailyChart: echarts.ECharts | null = null
let typeChart: echarts.ECharts | null = null

// 目标设置
const goalForm = ref({
  dailyMinutes: 60,
  weeklyHours: 7
})

// 计算属性
const dailyGoalProgress = computed(() => {
  if (!stats.value || !goalForm.value.dailyMinutes) return 0
  const todayMinutes = (stats.value.dailyStudyData[stats.value.dailyStudyData.length - 1]?.studyTimeSeconds || 0) / 60
  return Math.min(100, (todayMinutes / goalForm.value.dailyMinutes) * 100)
})

const weeklyGoalProgress = computed(() => {
  if (!stats.value || !goalForm.value.weeklyHours) return 0
  const weeklyMinutes = stats.value.dailyStudyData
    .slice(-7)
    .reduce((sum, day) => sum + (day.studyTimeSeconds || 0), 0) / 60
  return Math.min(100, (weeklyMinutes / (goalForm.value.weeklyHours * 60)) * 100)
})

const dailyStudyTime = computed(() => {
  if (!stats.value?.dailyStudyData.length) return '0分钟'
  const todaySeconds = stats.value.dailyStudyData[stats.value.dailyStudyData.length - 1]?.studyTimeSeconds || 0
  return formatDuration(todaySeconds)
})

const weeklyStudyTime = computed(() => {
  if (!stats.value?.dailyStudyData.length) return '0小时'
  const weeklySeconds = stats.value.dailyStudyData
    .slice(-7)
    .reduce((sum, day) => sum + (day.studyTimeSeconds || 0), 0)
  return `${Math.round(weeklySeconds / 3600)}小时`
})

const dailyGoalTime = computed(() => `${goalForm.value.dailyMinutes}分钟`)
const weeklyGoalTime = computed(() => `${goalForm.value.weeklyHours}小时`)

// 方法
const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

const getProgressColor = (percentage: number) => {
  if (percentage >= 100) return '#67c23a'
  if (percentage >= 80) return '#e6a23c'
  if (percentage >= 60) return '#409eff'
  return '#f56c6c'
}

const getRelativeProgress = (course: any, ranking: any[]) => {
  if (!ranking?.length) return 0
  const maxTime = ranking[0]?.studyTimeSeconds || 1
  return (course.studyTimeSeconds / maxTime) * 100
}

const getHeatmapIntensity = (hour: number) => {
  const hourData = stats.value?.hourlyData?.find(h => h.hour === hour)
  if (!hourData?.studyTimeSeconds) return 'intensity-0'
  
  const maxTime = Math.max(...(stats.value?.hourlyData?.map(h => h.studyTimeSeconds) || [1]))
  const intensity = (hourData.studyTimeSeconds / maxTime) * 100
  
  if (intensity >= 75) return 'intensity-4'
  if (intensity >= 50) return 'intensity-3'
  if (intensity >= 25) return 'intensity-2'
  if (intensity > 0) return 'intensity-1'
  return 'intensity-0'
}

const getHourStudyTime = (hour: number) => {
  const hourData = stats.value?.hourlyData?.find(h => h.hour === hour)
  return hourData?.formattedTime || '0分钟'
}

const loadStats = async () => {
  loading.value = true
  try {
    stats.value = await analyticsApi.getLearningStats(dailyChartDays.value)
    await nextTick()
    renderCharts()
  } catch (error: any) {
    ElMessage.error(error.message || '加载统计数据失败')
  } finally {
    loading.value = false
  }
}

const renderCharts = () => {
  renderDailyChart()
  renderTypeChart()
}

const renderDailyChart = () => {
  if (!dailyChartRef.value || !stats.value) return
  
  if (dailyChart) {
    dailyChart.dispose()
  }
  
  dailyChart = echarts.init(dailyChartRef.value)
  
  const option = {
    grid: {
      left: '10%',
      right: '10%',
      top: '15%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: stats.value.dailyStudyData.map(d => {
        const date = new Date(d.date)
        return `${date.getMonth() + 1}/${date.getDate()}`
      }),
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: '分钟',
      axisLabel: {
        formatter: (value: number) => Math.round(value / 60)
      }
    },
    series: [{
      type: 'bar',
      data: stats.value.dailyStudyData.map(d => d.studyTimeSeconds),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#409eff' },
          { offset: 1, color: '#66b3ff' }
        ])
      },
      barWidth: '60%'
    }],
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0]
        const minutes = Math.round(data.value / 60)
        return `${data.name}<br/>学习时长: ${minutes}分钟`
      }
    }
  }
  
  dailyChart.setOption(option)
}

const renderTypeChart = () => {
  if (!typeChartRef.value || !stats.value?.sessionTypeStats) return
  
  if (typeChart) {
    typeChart.dispose()
  }
  
  typeChart = echarts.init(typeChartRef.value)
  
  const data = Object.values(stats.value.sessionTypeStats).map(stat => ({
    name: stat.sessionType,
    value: stat.studyTimeSeconds
  }))
  
  const option = {
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data: data,
      label: {
        formatter: '{b}: {d}%'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }],
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const minutes = Math.round(params.value / 60)
        return `${params.name}<br/>时长: ${minutes}分钟 (${params.percent}%)`
      }
    },
    legend: {
      bottom: '10%',
      left: 'center'
    }
  }
  
  typeChart.setOption(option)
}

const saveGoals = () => {
  // TODO: 保存目标到后端
  ElMessage.success('学习目标已保存')
  showGoalDialog.value = false
}

// 生命周期
onMounted(() => {
  loadStats()
  
  // 响应式图表
  window.addEventListener('resize', () => {
    dailyChart?.resize()
    typeChart?.resize()
  })
})
</script>

<style scoped>
.progress-dashboard {
  padding: 20px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.study-time {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.study-days {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.courses {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.notes {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.course-ranking {
  padding: 10px 0;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.ranking-item:last-child {
  border-bottom: none;
}

.ranking-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #409eff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  margin-right: 12px;
}

.course-info {
  flex: 1;
  margin-right: 12px;
}

.course-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.study-time {
  font-size: 12px;
  color: #909399;
}

.progress-bar {
  width: 60px;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #66b3ff);
  transition: width 0.3s;
}

.heatmap-container {
  padding: 20px;
}

.heatmap-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 4px;
  margin-bottom: 16px;
}

.heatmap-cell {
  aspect-ratio: 1;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #fff;
  cursor: pointer;
  transition: transform 0.2s;
}

.heatmap-cell:hover {
  transform: scale(1.1);
}

.heatmap-cell.intensity-0 {
  background: #f0f0f0;
  color: #909399;
}

.heatmap-cell.intensity-1 {
  background: #c6e48b;
}

.heatmap-cell.intensity-2 {
  background: #7bc96f;
}

.heatmap-cell.intensity-3 {
  background: #239a3b;
}

.heatmap-cell.intensity-4 {
  background: #196127;
}

.heatmap-legend {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.legend-scale {
  display: flex;
  gap: 2px;
}

.legend-item {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-item.low {
  background: #c6e48b;
}

.legend-item.medium {
  background: #7bc96f;
}

.legend-item.high {
  background: #239a3b;
}

.legend-item.very-high {
  background: #196127;
}

.goals-card {
  margin-bottom: 20px;
}

.goals-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.goal-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.goal-icon {
  font-size: 32px;
  margin-right: 16px;
}

.goal-content {
  flex: 1;
}

.goal-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #303133;
}

.goal-progress {
  display: flex;
  align-items: center;
  gap: 12px;
}

.goal-progress :deep(.el-progress) {
  flex: 1;
}

.progress-text {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.empty-state {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-style: italic;
}
</style>
